/*
 * Copyright 2009 Brett Morgan.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.domesticmouse.waveoteditor.server;

import java.util.ArrayList;
import java.util.List;

import com.domesticmouse.waveoteditor.client.ops.InvalidFromVersion;
import com.domesticmouse.waveoteditor.client.wave.model.document.operation.AnnotationBoundaryMap;
import com.domesticmouse.waveoteditor.client.wave.model.document.operation.Attributes;
import com.domesticmouse.waveoteditor.client.wave.model.document.operation.BufferedDocInitialization;
import com.domesticmouse.waveoteditor.client.wave.model.document.operation.BufferedDocOp;
import com.domesticmouse.waveoteditor.client.wave.model.document.operation.DocInitializationCursor;
import com.domesticmouse.waveoteditor.client.wave.model.document.operation.algorithm.Composer;
import com.domesticmouse.waveoteditor.client.wave.model.document.operation.algorithm.Transformer;
import com.domesticmouse.waveoteditor.client.wave.model.document.operation.impl.DocOpBuilder;
import com.domesticmouse.waveoteditor.client.wave.model.document.operation.impl.DocOpUtil;
import com.domesticmouse.waveoteditor.client.wave.model.operation.OperationException;
import com.domesticmouse.waveoteditor.client.wave.model.operation.OperationPair;

/**
 * Class to represent the document under management. This class is responsible
 * for locking, cache management, etc.
 * 
 * @author brettmorgan
 * 
 */
public class Document {

	// Implement as a singleton before turning into a cache baby.
	private Document() {
		BufferedDocOp emptyDocument = new DocOpBuilder().build();
		editHistory.add(emptyDocument);
	}

	public final static Document instance = new Document();

	private List<BufferedDocOp> editHistory = new ArrayList<BufferedDocOp>();

	public synchronized BufferedDocOp getEditsFromVersion(int fromVersion) {
		if (fromVersion > editHistory.size()) {
			throw new InvalidFromVersion();
		} else if (fromVersion == editHistory.size()) {
			int documentSize = documentSize(DocOpUtil.asInitialization(Composer.compose(editHistory)));
			if (documentSize > 0) {
				return new DocOpBuilder().retain(documentSize).build();
			} else {
				return new DocOpBuilder().build();
			}
		} else {
			return Composer.compose(editHistory.subList(fromVersion, editHistory.size()));
		}
	}

	public synchronized BufferedDocOp addEditAt(BufferedDocOp clientEdit, int fromVersion) throws OperationException {
		if (fromVersion > editHistory.size()) {
			throw new InvalidFromVersion();
		} else if (fromVersion == editHistory.size()) {
			int documentSize = documentSize(DocOpUtil.asInitialization(Composer.compose(Composer.compose(editHistory), clientEdit)));
			editHistory.add(clientEdit);
			if (documentSize > 0) {
				return new DocOpBuilder().retain(documentSize).build();
			} else {
				return new DocOpBuilder().build();
			}
		} else {
			List<BufferedDocOp> releventEdits = editHistory.subList(fromVersion + 1, editHistory.size());
			// Transform the client edit past the server edits, then add it
			// at the end
			OperationPair<BufferedDocOp> transform = Transformer.transform(clientEdit, Composer.compose(releventEdits));
			DocOpUtil.asInitialization(Composer.compose(Composer.compose(editHistory), transform.clientOp()));
			editHistory.add(transform.clientOp());
			return transform.serverOp();
		}

	}

	public int getServerRevision() {
		// TODO Auto-generated method stub
		return editHistory.size();
	}

	private int documentSize(BufferedDocInitialization docInitilisation) {
		final int count[] = { 0 };
		docInitilisation.apply(new DocInitializationCursor() {

			@Override
			public void elementStart(String type, Attributes attrs) {
				count[0]++;
			}

			@Override
			public void elementEnd() {
				count[0]++;
			}

			@Override
			public void characters(String chars) {
				count[0] += chars.length();
			}

			@Override
			public void annotationBoundary(AnnotationBoundaryMap map) {
				count[0]++;
			}
		});
		return count[0];
	}

}
